package apoc.core.entity;

import apoc.core.ApocCore;
import apoc.core.network.packet.SyncPlayerPacket;
import apoc.core.plugin.ApocPlugin;
import apoc.core.plugin.PluginManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;

import java.util.HashMap;

public class ApocPlayerProperties implements IExtendedEntityProperties
{
    public static final String IDENTIFIER = "ApocServerProperties";
    private EntityPlayer player;
    private HashMap<String, PlayerProperties> properties;

    public ApocPlayerProperties()
    {
        properties = new HashMap<String, PlayerProperties>();
        for (ApocPlugin plugin : PluginManager.plugins())
            if (plugin.getPlayerProperties(this) != null)
                properties.put(plugin.getId(), plugin.getPlayerProperties(this));
    }

    public static ApocPlayerProperties getByEntity(EntityPlayer player)
    {
        if (player.getExtendedProperties(IDENTIFIER) == null)
            player.registerExtendedProperties(IDENTIFIER,
                    new ApocPlayerProperties());
        ApocPlayerProperties properties = (ApocPlayerProperties) player.getExtendedProperties(IDENTIFIER);
        return properties;
    }

    public static PlayerProperties getPluginProperties(String key, EntityPlayer player)
    {
        return getByEntity(player).getProperties(key);
    }

    public void sync()
    {
        if (player != null)
            if (!player.worldObj.isRemote)
                ApocCore.packetPipeline.sendToDimension(new SyncPlayerPacket(player), player.worldObj.provider.dimensionId);
    }

    public PlayerProperties getProperties(String id)
    {
        return properties.get(id);
    }

    @Override
    public void saveNBTData(NBTTagCompound compound)
    {
        for (PlayerProperties properties : this.properties.values())
        {
            properties.saveNBTData(compound);
        }
    }

    @Override
    public void loadNBTData(NBTTagCompound compound)
    {
        for (PlayerProperties properties : this.properties.values())
        {
            properties.loadNBTData(compound);
        }
    }

    @Override
    public void init(Entity entity, World world)
    {
        this.player = (EntityPlayer) entity;
    }
}
